package cn.edu.cqvie.atc.search;

import static java.util.Arrays.stream;

public class Search {

    public static void main(String[] args) {
        Search search = new Search();
        int[] arr = new int[]{1, 3, 4, 7, 9, 10};
        stream(arr).forEach(a -> {
            System.out.print(a + " ");
        });
        System.out.println();
        int val = 9;
        System.out.println("search " + val  + " index=" + search.binarySearch(arr, val));
    }

    /**
     * 二分查找，基于排序数组
     * @param arr
     * @param value
     * @return
     */
    public int binarySearch(int[] arr, int value) {
        int middle = 0, pow = arr.length - 1, low = 0;
        while (true) {
            middle = (pow + low) / 2;
            if (arr[middle] == value) {
                return middle;
            } else if (low > pow) {
                return -1;
            } else {
                if (arr[middle] > value) {
                    pow = middle - 1;
                } else {
                    low = middle + 1;
                }

            }

        }
    }
}
